/*
 * 	<pre>
 *	EasyPeas.
 *  Copyright (C) 2007 S Owen
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * Jul 24, 2007
 * EasyPeasServlet.java
 * </pre>
 */
package org.easypeas.http;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.easypeas.EasyPeasConstants;
import org.easypeas.util.Timer;

/**
 * The Servlet that handled the processing of a GET or POST and delegates the
 * request and response to an {@link Invoker} to be processed.<br>
 * <br>
 * After execution of a View or Action, the resulting map is processed by a
 * template engine. The current template engine is hard wired as Velocity.<br>
 * The location of these templates is defined by
 * <code>easypeas.resource.loader.path</code> and is relative to the context
 * root. If missing it default to <em>templates</em>. <br>
 * <br>
 * 
 * If a path includes a "." it is passed on to the default dispatcher, and not
 * processed by this servlet. This means the EasyPea paths cannot include "."'s<br>
 * but allows .html, .jsp etc, files to be mixed with EasyPea views and actions.
 * 
 * @see Invoker
 * @author S Owen
 * 
 */
public class EasyPeasServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {

	private static final long serialVersionUID = 5455973183896867222L;

	private static Logger logger = Logger.getLogger("org.easypeas.http.EasyPeasServlet");
        
        private boolean welcomeFileDefined=false;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String templatePath;
		if (getInitParameter("easypeas.resource.loader.path") == null) {
			logger.info("Using default template path: templates");
			templatePath = "templates";
		} else {
			templatePath = getInitParameter("easypeas.resource.loader.path");
			logger.info("Using template path:" + templatePath);
		}
		if (getInitParameter(EasyPeasConstants.EASYPEA_INVOKER) != null) {
			logger.info("Using " + EasyPeasConstants.EASYPEA_INVOKER + "="
					+ getInitParameter(EasyPeasConstants.EASYPEA_INVOKER));
			System.setProperty(EasyPeasConstants.EASYPEA_INVOKER,
					getInitParameter(EasyPeasConstants.EASYPEA_INVOKER));
		}
		if (getInitParameter(EasyPeasConstants.EASYPEA_MAPPINGS) != null) {
			logger.info("Using " + EasyPeasConstants.EASYPEA_MAPPINGS + "="
					+ getInitParameter(EasyPeasConstants.EASYPEA_MAPPINGS));
			System.setProperty(EasyPeasConstants.EASYPEA_MAPPINGS,
					getInitParameter(EasyPeasConstants.EASYPEA_MAPPINGS));
		}
		EasyPeasHandler.init(getServletContext(), templatePath);
                
                String wfd=getInitParameter("welcome-file-defined");
                welcomeFileDefined=wfd!=null && wfd.equals("true");
	}

	/**
	 * {@inheritDoc}
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		logger.finer("IN GET: " + request.getRequestURI());
		
                String path = request.getRequestURI().replaceFirst(
				request.getContextPath(), "");
		if (EasyPeasHandler.canHandle(path,getServletContext()) || !welcomeFileDefined) {
			Timer timer = Timer.getTimer();
			timer.start();

			EasyPeasHandler.getInstance().handleView(request, response, path);

			timer.stop();
			logger.finer("Request timing info: " + timer);
		} else {
			passToDefaultDispatcher(request, response);
		}
	}

	private void passToDefaultDispatcher(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		getServletContext().getNamedDispatcher("default").forward(request,
				response);
	}

	/**
	 * {@inheritDoc}
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		logger.finer("IN POST \n" + request);		
		String path = request.getRequestURI().replaceFirst(
				request.getContextPath(), "");
		EasyPeasHandler.getInstance().handleAction(request, response, path);
	}

}
